

package org.argeproje.resim;

import java.lang.reflect.InvocationTargetException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.argeproje.resim.proc.tools.LoggerUT;
import org.argeproje.resim.ui.rcp.ApplicationWorkbenchAdvisor;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.equinox.app.IApplication;
import org.eclipse.equinox.app.IApplicationContext;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.PlatformUI;
import org.eclipse.update.configuration.IConfiguredSite;
import org.eclipse.update.configuration.ILocalSite;
import org.eclipse.update.core.IFeatureReference;
import org.eclipse.update.core.ISite;
import org.eclipse.update.core.SiteManager;
import org.eclipse.update.core.VersionedIdentifier;
import org.eclipse.update.operations.IInstallFeatureOperation;
import org.eclipse.update.operations.OperationsManager;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.wizard.ProgressMonitorPart;


/**
 * This class controls all aspects of the application's execution
 */
public class Application implements IApplication {

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.eclipse.equinox.app.IApplication#start(org.eclipse.equinox.app.IApplicationContext)
	 */
	public Object start(IApplicationContext context) throws Exception {
		Display display = PlatformUI.createDisplay();
		;
		;
		try {			
			LoggerUT.init();
			
			try {
				if(checkForUpdates(display.getActiveShell()))
					return IApplication.EXIT_RESTART;
			} catch (Exception e) {
				//MessageDialog.openError(display.getActiveShell(),"Update Manager Error", e.getMessage());
			}
			
			int returnCode = PlatformUI.createAndRunWorkbench(display,
					new ApplicationWorkbenchAdvisor());
			
			if (returnCode == PlatformUI.RETURN_RESTART)
				return IApplication.EXIT_RESTART;
			else
				return IApplication.EXIT_OK;
		} finally {
			display.dispose();
		}

	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.eclipse.equinox.app.IApplication#stop()
	 */
	public void stop() {
		final IWorkbench workbench = PlatformUI.getWorkbench();
		if (workbench == null)
			return;
		final Display display = workbench.getDisplay();
		display.syncExec(new Runnable() {
			public void run() {
				if (!display.isDisposed())
					workbench.close();
			}
		});
	}
	
	private boolean checkForUpdates(Shell shell) throws MalformedURLException, CoreException, InvocationTargetException
	{
		IProgressMonitor monitor = new NullProgressMonitor();
		try
		{
			String url = "http://www.argeproje.com/download/releases/linux/updates/";
		    ISite rs = SiteManager.getSite(new URL(url), monitor);
		    monitor.worked(10);
			IFeatureReference[] frs = rs.getFeatureReferences();
			monitor.worked(20);
			ILocalSite ls = SiteManager.getLocalSite();
			IConfiguredSite ics = ls.getCurrentConfiguration().getConfiguredSites()[0];
			IFeatureReference[] lfrs = ics.getConfiguredFeatures();
			List<IInstallFeatureOperation> installOps = new ArrayList<IInstallFeatureOperation>();
			monitor.worked(30);
			for (int i = 0; i < frs.length; i++) {
				for (int j = 0; j < lfrs.length; j++) {
			 		VersionedIdentifier frsVi = frs[i].getVersionedIdentifier();
			 		VersionedIdentifier lfrsVi = lfrs[j].getVersionedIdentifier();
						 		
			 		if (frsVi.getIdentifier().equals(lfrsVi.getIdentifier())) {
			
			 			if (frsVi.getVersion().isGreaterThan(lfrsVi.getVersion())) {
			
			 				installOps.add(OperationsManager.getOperationFactory().createInstallOperation(
			 					ics, frs[i].getFeature(monitor), null, null, null));
			 			}
			 		}
			 	}
			 }
			
			if (installOps.size() > 0) {
				if(MessageDialog.openConfirm(shell, "", "Install new update?"))
				{
					int index = 0;
					int totalWork = 0;
					for (Iterator<IInstallFeatureOperation> iter = installOps.iterator(); iter.hasNext();) {
						index++;
						IInstallFeatureOperation op = (IInstallFeatureOperation) iter.next();
				 		op.execute(monitor, null);
				 		totalWork = (int)(30+(70/installOps.size())*index);
				 		if(totalWork>=100) 
				 		{
				 			totalWork = 100;
				 		}
				 		monitor.worked(totalWork);			 		
				 	}
				 	ls.save();
				 	return true;
				}
			}
		}
		finally
		{
			monitor.done();
		}
		return false;
	}
	
}
